<?php
// post type for gallery
$labels = array(
    'name'                  => _x('Photo Albums', 'post type general name', LANGUAGE_ZONE),
    'singular_name'         => _x('Photo Album', 'post type singular name', LANGUAGE_ZONE),
    'add_new'               => _x('Add New', 'post type new', LANGUAGE_ZONE),
    'add_new_item'          => __('Add New Album', LANGUAGE_ZONE),
    'edit_item'             => __('Edit Album', LANGUAGE_ZONE),
    'new_item'              => __('New Album', LANGUAGE_ZONE),
    'view_item'             => __('View Album', LANGUAGE_ZONE),
    'search_items'          => __('Search for Albums', LANGUAGE_ZONE),
    'not_found'             =>  __('No Albums Found', LANGUAGE_ZONE),
    'not_found_in_trash'    => __('No Albums Found in Trash', LANGUAGE_ZONE), 
    'parent_item_colon'     => '',
    'menu_name'             => 'Photo Albums'

);

$args = array(
    'labels'                => $labels,
    'public'                => false,
    'publicly_queryable'    => false,
    'show_ui'               => true, 
    'show_in_menu'          => true, 
    'query_var'             => true,
    'rewrite'               => true,
    'capability_type'       => 'post',
    'has_archive'           => false, 
    'hierarchical'          => false,
    'menu_position'         => 28,
    'menu_icon'		        => get_template_directory_uri(). '/images/admin_ico_gallery.png',
    'supports'              => array( 'title', 'thumbnail', 'excerpt' )
);
 
register_post_type( 'dt_gallery', $args );
// post type end

// TAXONOMY
$labels = array(
    'name'              => _x( 'Categories', 'taxonomy general name', LANGUAGE_ZONE ),
    'singular_name'     => _x( 'Category', 'taxonomy singular name', LANGUAGE_ZONE ),
    'search_items'      => __( 'Search in Category', 'dt' ),
    'all_items'         => __( 'Categories', 'dt' ),
    'parent_item'       => __( 'Parent Category', 'dt' ),
    'parent_item_colon' => __( 'Parent Category:', 'dt' ),
    'edit_item'         => __( 'Edit Category', 'dt' ), 
    'update_item'       => __( 'Update Category', 'dt' ),
    'add_new_item'      => __( 'Add New Category', 'dt' ),
    'new_item_name'     => __( 'New Category Name', 'dt' ),
    'menu_name'         => __( 'Categories', 'dt' ),
); 	

register_taxonomy(
    'dt_gallery_category',
    array( 'dt_gallery' ),
    array(
        'hierarchical'          => true,
        'show_in_nav_menus '    => false,
        'public'                => false,
        'show_tagcloud'         => false,
        'labels'                => $labels,
        'show_ui'               => true,
        'rewrite'               => true
    )
);
// TAXONOMY end

// metaboxez
add_action( 'add_meta_boxes', 'dt_gallery_boxes' );

// Do something with the data entered
add_action( 'save_post', 'dt_gallery_list_save' );
add_action( 'save_post', 'dt_gallery_order_save' );

function dt_gallery_boxes() {
    add_meta_box(
        'gallery-order_options',
        __( 'Custom gallery options', LANGUAGE_ZONE ),
        'dt_gallery_orber_box',
        'dt_gallery',
        'advanced',
        'low'
    );
    
    add_meta_box(
        'gallery-admin',
        __( 'Gallery', LANGUAGE_ZONE ),
        'dt_gallery_admin_box',
        'dt_gallery',
        'advanced',
        'high'
    );
    
    if ( isset($_GET['post']) ) {
        $post_id = $_GET['post'];
    } elseif ( isset($_POST['post_ID']) ) {
        $post_id = $_POST['post_ID'];
    } else
        return;

    $template_file = get_post_meta($post_id,'_wp_page_template',TRUE);

    // check for a template type
    if ( ($template_file == 'dt_gallery.php') || ($template_file == 'dt_photos.php') ) {
        add_meta_box(
            'gallery-list',
            __( 'Gallery options', LANGUAGE_ZONE ),
            'dt_gallery_list_box',
            'page'
        );
    }
}

function dt_gallery_list_box( $post ) {
    $box_name = 'dt_gallery_layout';
    
    $terms = get_categories(
        array(
            'type'                     => 'dt_gallery',
            'hide_empty'               => 1,
            'hierarchical'             => 0,
            'taxonomy'                 => 'dt_gallery_category',
            'pad_counts'               => false
        )
    );
       
    $defaults = array(
        'list'      => array(),
        'ppp'       => '',
        'orderby'   => 'date',
        'order'     => 'DESC',
        'slug'      => 'gal_cats'
    );
    
    $options = get_post_meta( $post->ID, $box_name, true );
    $options = wp_parse_args( $options, $defaults );
    
    // Use nonce for verification
    wp_nonce_field( plugin_basename( __FILE__ ), $box_name. '_nonce' );
        
    ?>
    
    <?php
    // print select list
    dt_admin_select_list(
        array(
            'rad_butt_name' => 'show_type_gallery',
            'checkbox_name' => 'show_gallery',
            'terms'         => &$terms,
            'current_sel'   => $options['list'],
            'con_class'     => 'gallery-list'
        )    
    );
    ?>
    
    <hr/>
    
    <?php
    // posts_per_page
    dt_admin_ppp_options(
        array(
            'options'   => $options,
            'box_name'  => $box_name
        )
    );
    ?>

    <hr/>
    
    <?php
    // print order options
    dt_admin_order_options(
        array(
            'options'   => $options,
            'box_name'  => $box_name
        )
    );
    ?>
    
    <?php
}

function dt_gallery_list_save( $post_id ) {
    $box_name = 'dt_gallery_layout';
    // verify if this is an auto save routine. 
    // If it is our form has not been submitted, so we dont want to do anything
  
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return;

    // verify this came from the our screen and with proper authorization,
    // because save_post can be triggered at other times

    if ( !isset( $_POST[$box_name. '_nonce'] ) || !wp_verify_nonce( $_POST[$box_name. '_nonce'], plugin_basename( __FILE__ ) ) )
        return;

  
    // Check permissions
    if ( !current_user_can( 'edit_page', $post_id ) )
        return;
    
    $mydata = null;
    switch( $_POST['show_type_gallery'] ) {
        case 'only':
            if( isset($_POST['show_gallery']['only']) ) {
                $mydata['list']['only'] = $_POST['show_gallery']['only'];
            }
            break;
        case 'except':
            if( isset($_POST['show_gallery']['except']) ) {
                $mydata['list']['except'] = $_POST['show_gallery']['except'];
            }
            break;
        default:
            $mydata['list'] = null;
    }
    
    if( !empty($_POST[$box_name. '_ppp']) ) {
        $mydata['ppp'] = intval($_POST[$box_name. '_ppp']);
    }
    
    if( isset($_POST[$box_name. '_orderby']) ) {
        $mydata['orderby'] = $_POST[$box_name. '_orderby'];
    }
    
    if( isset($_POST[$box_name. '_order']) ) {
        $mydata['order'] = $_POST[$box_name. '_order'];
    }
    
    update_post_meta( $post_id, $box_name, $mydata );
}

function dt_gallery_orber_box( $post ) {
    $box_name = 'dt_gallery_order';
    $defaults = array(
        'orderby'           => 'menu_order',
        'order'             => 'ASC',
        'hide_thumbnail'    => false
    );
    $opts = get_post_meta( $post->ID, $box_name, true );
    $opts = wp_parse_args( $opts, $defaults );
    
    // Use nonce for verification
    wp_nonce_field( plugin_basename( __FILE__ ), $box_name. '_nonce' );
    ?>
    
    <p>
        <label for="<?php echo $box_name; ?>_hide_thumbnail">
            <input id="<?php echo $box_name; ?>_hide_thumbnail" type="checkbox" name="<?php echo $box_name; ?>_hide_thumbnail" <?php echo checked($opts['hide_thumbnail']); ?>/>
            <?php _e( 'Exclude featured image from gallery', LANGUAGE_ZONE ); ?>
        </label>
    </p>
    
    <?php
    dt_admin_order_options(
        array(
            'options'   => $opts,
            'box_name'  => $box_name
        )
    );
}

function dt_gallery_order_save( $post_id ) {
    $box_name = 'dt_gallery_order';
    // verify if this is an auto save routine. 
    // If it is our form has not been submitted, so we dont want to do anything
  
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return;

    // verify this came from the our screen and with proper authorization,
    // because save_post can be triggered at other times

    if ( !isset( $_POST[$box_name. '_nonce'] ) || !wp_verify_nonce( $_POST[$box_name. '_nonce'], plugin_basename( __FILE__ ) ) )
        return;

  
    // Check permissions
    if ( !current_user_can( 'edit_page', $post_id ) )
        return;
    
    $mydata = null;

    if( isset($_POST[$box_name. '_orderby']) ) {
        $mydata['orderby'] = $_POST[$box_name. '_orderby'];
    }
    
    if( isset($_POST[$box_name. '_order']) ) {
        $mydata['order'] = $_POST[$box_name. '_order'];
    }
    
    $mydata['hide_thumbnail'] = isset( $_POST[$box_name. '_hide_thumbnail'] );
    
    update_post_meta( $post_id, $box_name, $mydata );
}


// custom tab -------------------------------------------------------------------
// action: dt_media_tab
// filter: dt_media_upload_tab_filter
// media upload fumctions
function dt_gallery_admin_box( $post ) {

    $tab = 'type';
    $args = array(
        'post_type'			=>'attachment',
        'post_status'		=>'inherit',
        'post_parent'		=>$post->ID,
        'posts_per_page'	=>1
    );
    $attachments = new Wp_Query( $args );

    if( !empty($attachments->posts) ) {
        $tab = 'dtmedia';
    }
    
    $u_href = get_admin_url();
    $u_href .= '/media-upload.php?post_id='. $post->ID;
    $u_href .= '&width=670&height=400&tab='.$tab;
?>
    <iframe src="<?php echo esc_url($u_href); ?>" width="100%" height="560">The Error!!!</iframe>
<?php
}

function dt_media_form( $errors ) {
    global $redir_tab, $type;

    $redir_tab = 'dtmedia';
    media_upload_header();
    
    $post_id = intval($_REQUEST['post_id']);
    $form_action_url = admin_url("media-upload.php?type=$type&tab=dtmedia&post_id=$post_id");
    $form_action_url = apply_filters('media_upload_form_url', $form_action_url, $type);
    $form_class = 'media-upload-form validate';
    
    if ( get_user_setting('uploader') )
        $form_class .= ' html-uploader';
?>	
    <script type="text/javascript">
    <!--
    jQuery(function($){
        var preloaded = $(".media-item.preloaded");
        if ( preloaded.length > 0 ) {
            preloaded.each(function(){prepareMediaItem({id:this.id.replace(/[^0-9]/g, '')},'');});
            updateMediaForm();
        }
    });
    -->
    </script>
    <div id="sort-buttons" class="hide-if-no-js">
    <span>
    <?php _e('All Tabs:'); ?>
    <a href="#" id="showall"><?php _e('Show'); ?></a>
    <a href="#" id="hideall" style="display:none;"><?php _e('Hide'); ?></a>
    </span>
    <?php _e('Sort Order:'); ?>
    <a href="#" id="asc"><?php _e('Ascending'); ?></a> |
    <a href="#" id="desc"><?php _e('Descending'); ?></a> |
    <a href="#" id="clear"><?php _ex('Clear', 'verb'); ?></a>
    </div>
    <form enctype="multipart/form-data" method="post" action="<?php echo esc_attr($form_action_url); ?>" class="<?php echo $form_class; ?>" id="gallery-form">
    <?php wp_nonce_field('media-form'); ?>
    <?php //media_upload_form( $errors ); ?>
    <table class="widefat" cellspacing="0">
    <thead><tr>
    <th><?php _e('Media'); ?></th>
    <th class="order-head"><?php _e('Order'); ?></th>
    <th class="actions-head"><?php _e('Actions'); ?></th>
    </tr></thead>
    </table>
    <div id="media-items">
    <?php add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2); ?>
    <?php $_REQUEST['tab'] = 'gallery'; ?>
    <?php echo get_media_items($post_id, $errors); ?>
    <?php $_REQUEST['tab'] = 'dtmedia';?>
    </div>

    <p class="ml-submit">
    <?php submit_button( __( 'Save all changes' ), 'button savebutton', 'save', false, array( 'id' => 'save-all', 'style' => 'display: none;' ) ); ?>
    <input type="hidden" name="post_id" id="post_id" value="<?php echo (int) $post_id; ?>" />
    <input type="hidden" name="type" value="<?php echo esc_attr( $GLOBALS['type'] ); ?>" />
    <input type="hidden" name="tab" value="<?php echo esc_attr( $GLOBALS['tab'] ); ?>" />
    </p>
    </form>
<?php
}